<?php
/**
 * Author: ChenGuangHui
 * Email：13035809409@163.com
 * Date Time: 2021/9/6 17:06
 */


namespace App\Logic\Notice;


use App\Enums\HttpCode;
use App\Logic\CommLogic;
use App\Models\Notice\Notice;
use App\Models\Notice\NoticeClass;

class NoticeClassLogic extends CommLogic
{
    /**
     * @param $params
     * @return array
     */
    public function lists($params)
    {
        $list = NoticeClass::query()
            ->orderByDesc('created_at')
            ->get()->toArray();

        $notice = Notice::query()->where('staffer_id', auth('api')->id())->get();
        foreach ($list as &$item) {
            $item['count'] = collect($notice)->where('class_id', $item['id'])->count();
            $item['children'] = array_values(collect($notice)->where('class_id', $item['id'])->all());
        }

        return $list;
    }

    /**
     * @param $params
     * @return \App\Models\Model|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model
     */
    public function store($params)
    {
        $lockName = 'notice_store_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');
        $data = array(
            'staffer_id' => auth('api')->id(),
            'class_name' => $params['class_name'],
        );
        return NoticeClass::query()->create($data);
    }

    /**
     * @param $params
     * @param $id
     * @return bool|int
     */
    public function update($params, $id)
    {
        $lockName = 'notice_update_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');
        $class = NoticeClass::query()->where('id', $id)->first();
        abort_if(empty($class), HttpCode::FORBIDDEN, '分类不存在！');
        $data = array(
            'class_name' => $params['class_name']
        );
        return NoticeClass::query()->where('id', $id)->update($data);
    }

    /**
     * @param $id
     * @return bool|mixed|null
     */
    public function destroy($id)
    {
        $data = NoticeClass::query()->where('id', $id)->first();
        abort_if(empty($data), HttpCode::FORBIDDEN, '分类不存在！');
        Notice::query()->where('class_id', $id)->update(['status' => 1]);
        return NoticeClass::query()->where('id', $id)->delete();
    }
}
